package com.wstuo.common.security.dao;

import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.security.entity.Company;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * 公司信息DAO方法.
 * @author will
 */
public class CompanyDAO
    extends BaseDAOImplHibernate<Company>
    implements ICompanyDAO
{
	
	@Autowired
	private IOrganizationDAO organizationDAO;
	
    /**
     * 查找顶级公司信息.
     * @return 公司集合List<Company>
     */
    public List<Company> findATree(){
        @SuppressWarnings( "unchecked" )
        List<Company> companys = super.getHibernateTemplate().find( " from Company com where com.parentOrg IS NULL" );

        return companys;
    }

    /**
     * 查找公司信息.
     * @param companyNo
     * @return 公司信息 Company
     */
    public Company findCompany(Long companyNo){
    	Company company = null;
    	if(companyNo==0){//默认，未指定公司
	        List<Company> companys = super.findAll();
	        if (!companys.isEmpty() ){
	        	company = companys.get(0);
	        }
    	}else{//查找指定的公司
    		company = super.findById(companyNo);
    	}
    	return company;
    }
    
    
    /**
     * 重写SAVE方法.
     * @param entity
     */
     @Override
     public void save(Company entity){

     	if(entity.getOrgNo()==null || entity.getOrgNo()==0){
     		entity.setOrgNo(organizationDAO.getLatestOrganizationNo());
     		
     	}else{
     		
     		if(entity.getOrgNo()>organizationDAO.getLatestOrganizationNo()){
     			
     			organizationDAO.setLatesOrganizationNo(entity.getOrgNo());
     		}
     	}
     	super.save(entity);
     	organizationDAO.increment();//自增1.
     	
     }
     
     /**
      * 重写Merge方法
      * @param entity
      */
     @Override
     public Company merge(Company entity){
    	 
    	if(entity.getOrgNo()!=null){
    		
    		if(entity.getOrgNo()>=organizationDAO.getLatestOrganizationNo()){
    			organizationDAO.setLatesOrganizationNo(entity.getOrgNo()+1);
    		}
    		
    	}else{
    		organizationDAO.increment();//自增1.
  		}
    	 
    	return super.merge(entity);
     }
     
    
}
